﻿using Ledict.ConditionExtract.BLL.LuceneSearchApi;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.DAL;
using Ledict.ConditionExtract.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace Ledict.ConditionExtract.BLL.WorkProcess
{
    /// <summary>
    /// 第一次处理刑事
    /// </summary>
    public class WorkThread_first_Crime : WorkThread_first
    {
        public int MaxCount = 0;//处理总数
        private int _currentCount = 0;//处理当前数量

        protected TreeDataBLL trbll = new TreeDataBLL();
        protected Express_WordBLL wordbll = new Express_WordBLL();
        protected Express_AddElement addelementbll = new Express_AddElement();
        protected ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        protected AboutRegexBLL aboutreg = new AboutRegexBLL();
        protected RegexParse.RegexParse getregex = new RegexParse.RegexParse();
        protected ProcessDataSourceBLL datas = new ProcessDataSourceBLL();
        protected WorkThread_Public work = new WorkThread_Public();
        protected XmlLabel_LabelRelBLL xmlLabel_LabelRelBLL = new XmlLabel_LabelRelBLL();
        //private CaseCauseBLL casecausebll = new CaseCauseBLL();
        private StaticCacheBLL staticcache = new StaticCacheBLL();
        //Express_MatchSituationBLL MatchSituationbll = new Express_MatchSituationBLL();
        //WordBankKeyWordsBLL wordbankkeywordsbll = new WordBankKeyWordsBLL();
        NewIDBLL newid = new NewIDBLL();
        Express_WordBankRelBLL express_wordbankrelbll = new Express_WordBankRelBLL();
        PresentationResultsBLL presentationbll = new PresentationResultsBLL();
        Express_MatchSituationBLL MatchSituationbll = new Express_MatchSituationBLL();

        #region  准备开始
        /// <summary>
        /// 开始加工（一个案由）
        /// </summary>
        public override void execute_Start()
        {
            //打开缓存
            getregex.StartCache();
            //查询案由的案由路径-查询案例库
            conditon.HeadwordId = trbll.GetHeadWordAllPid(conditon.HeadwordId);
            MaxCount = 0;
            _currentCount = 0;
            //2、待处理的数据(总数)-查询lucene索引
            MaxCount += GetDataSourceCount(conditon);

            //没有可以跑数据的案例
            // 没数据结束进度条
            if (MaxCount == 0)
            {
                if (MaxCount >= _currentCount)
                {
                    processShow(MaxCount, _currentCount);
                }
            }
            else//开始加工数据
            {
                execute_Condition(conditon);
            }
            //关闭缓存
            getregex.EndCache();
        }




        #endregion

        #region  准备条件和数据
        /// <summary>
        /// 加工数据
        /// 1、由“查询条件”（condition）查询lucene索引，得到“表述”
        /// 2、由“处理节点”(condition.SituationId)获得“情形情节分组”(如：犯罪相关情形、法定情节)
        ///     2.1根据处理节点如果节点的类型是案由，则获取该案由下的节点属性中匹配表述根节点的节点，如果该节点的属性为匹配表述根节点，返回该节点，否则一次向上级找，直到找到匹配表述根节点的节点集合。
        ///     2.2 从索引中分页查询数据 第一页判断是否存在单一和组合节点，不存在则添加单一和组合节点（判断存在语句问题）
        /// 3、由“情形情节分组”（2的结果）查询数据库，得到节点的范围   (如：犯罪相关情形的所有下级节点)
        /// 4、匹配数据。过程：用“表述”（1的结果）匹配“节点”（3的结果），得出结果，结果如：
        ///    盗窃数额较大(单一)            --被告人秘密窃取他人财物，数额较大，其行为已构成盗窃罪，依法应予惩处。
        ///    盗窃数额较大+结伙盗窃（组合） --被告人伙同他人秘密窃取公私财物，数额较大，其行为已构成盗窃罪，依法应予惩处。
        /// 5、匹配后的结果入库。
        ///    表述节点（如：盗窃数额较大、盗窃数额较大+结伙盗窃）存入SYS_Express_MatchSituation
        ///    表述文本（如：被告人秘密窃取他人财物，数额较大，其行为已构成盗窃罪，依法应予惩处。）存入SYS_Express_Word_Process
        /// </summary>
        /// <param name="condition">条件</param>
        public virtual void execute_Condition(DataSourceCondition condition)
        {
            int perPage = condition.SearchPerSize; //每次从索引取5000条
            int page = (int)Math.Ceiling((double)MaxCount / perPage);//多少页

            //2.情形情节分组
            string caseCauseId = string.Empty;
            DataTable processNodedt = work.BelongCaseCauseId(condition.SituationId, out caseCauseId);//节点匹配数据开始处 --数据库
            string singleCCID = string.Empty;
            string doubleCCID = string.Empty;
            #region 分页

            for (int pag = 1; pag <= page; pag++)//分页
            {
                //1.由“查询条件”（condition）查询lucene索引，得到“表述”
                DataTable caseiddtLucene = GetDataSource(condition, pag, perPage);//分页数据源集合（索引获取）
                if (caseiddtLucene != null && caseiddtLucene.Rows.Count > 0 && processNodedt != null && processNodedt.Rows.Count > 0)
                {
                    #region MyRegion
                    //if (pag == 1)//添加组合单一节点
                    //{
                    //    work.AddMatch_virtual("S" + processNodedt.Rows[0]["CC_ID"].ToString(), "单一");
                    //    work.AddMatch_virtual("M" + processNodedt.Rows[0]["CC_ID"].ToString(), "组合");
                    //    singleCCID = processNodedt.Rows[0]["AllParentId"].ToString() + ",S" + processNodedt.Rows[0]["CC_ID"].ToString();
                    //    doubleCCID = processNodedt.Rows[0]["AllParentId"].ToString() + ",M" + processNodedt.Rows[0]["CC_ID"].ToString();
                    //}

                    // IEnumerable<DataRow> caseidenumerable = caseiddtLucene.Rows.Cast<DataRow>();
                    //int indextemp = -1;

                    //Parallel.ForEach(caseidenumerable, new ParallelOptions
                    //{
                    //    MaxDegreeOfParallelism = 2
                    //},
                    //row =>
                    //{
                    # endregion

                    for (int i = 0; i < caseiddtLucene.Rows.Count; i++)
                    {
                        //int k = Interlocked.Add(ref indextemp, 1);

                        for (int p = 0; p < processNodedt.Rows.Count; p++)//小单元
                        {
                            if (pag == 1)//添加组合单一节点
                            {
                                work.AddMatch_virtual("S" + processNodedt.Rows[p]["CC_ID"].ToString(), "单一");
                                work.AddMatch_virtual("M" + processNodedt.Rows[p]["CC_ID"].ToString(), "组合");
                                singleCCID = processNodedt.Rows[p]["AllParentId"].ToString() + ",S" + processNodedt.Rows[p]["CC_ID"].ToString();
                                doubleCCID = processNodedt.Rows[p]["AllParentId"].ToString() + ",M" + processNodedt.Rows[p]["CC_ID"].ToString();
                            }


                            string processNodeId = processNodedt.Rows[p]["CC_ID"].ToString();//小单元起始处
                            string paragraphId = caseiddtLucene.Rows[i]["ParagraphTypeId"].ToString(); //row["ParagraphTypeId"].ToString();//
                            string caseid = caseiddtLucene.Rows[i]["CaseId"].ToString();//案例IDrow["CaseId"].ToString();//案例ID//
                            string paragraphText = caseiddtLucene.Rows[i]["ParagraphText"].ToString();//row["ParagraphText"].ToString();//
                                                                                                      //2017-6-21 ljj 修改，从索引中获取隐私处理数据
                            string fieldValue = caseiddtLucene.Rows[i]["FieldValue"].ToString();//row["FieldValue"].ToString();//
                            paragraphText = Privacy(paragraphText, fieldValue);
                            //隐私处理
                            //paragraphText = "被告人×××无驾驶资格驾驶机动车，酌情予以从重处罚。";
                            //todo by zhangpeng:在加入关键字匹配后，需要修改存储过程sp_CondiExt_GetCauseDataSource
                            //3.由“情形情节分组”（2的结果）查询数据库，得到节点的范围   (如：犯罪相关情形的所有下级节点)
                            DataTable conditiondt = staticcache.GetHeadwordData(processNodeId, processNodedt.Rows[p]["CC_ParentID"].ToString());//节点信息集合 
                                                                                                                                                //4.匹配数据
                            execute_Match(paragraphText, caseid, paragraphId, processNodeId, conditiondt, singleCCID, doubleCCID, caseCauseId);

                            #region 提前筛选数据 尽可能匹配当前节点的表述，不符合要求的直接舍弃
                            //bool flog = true;
                            //DataRow[] arrayDrPro = conditiondt.Select("CC_ID='" + condition.SituationId + "'");
                            //if (arrayDrPro.Any() && Convert.ToInt32(arrayDrPro[0]["RegCount"].ToString()) > 0)//有正则
                            //{
                            //    flog = IsMatch(paragraphText, arrayDrPro[0]["CC_RegexInfoCode"].ToString()) > 0;
                            //}
                            //

                            //if (flog)
                            //{
                            ////4.匹配数据
                            //execute_Match(paragraphText, caseid, paragraphId, processNodeId, conditiondt, singleCCID, doubleCCID);
                            //}
                            #endregion 提前筛选数据
                        }
                        #region 处理完成后,进度条

                        _currentCount++; // 显示进度条
                        if (MaxCount >= _currentCount)
                        {
                            processShow(MaxCount, _currentCount);
                        }

                        int innercurrentcout = Interlocked.Add(ref this._currentCount, 1);
                        if (this.MaxCount >= innercurrentcout)
                        {
                            this.processShow(this.MaxCount, innercurrentcout);
                        }

                        lockObj.WaitOne();
                        if (readyToClose)
                        {
                        }

                        #endregion 处理完成后,进度条
                        //});
                    }
                }
            }

            #endregion 分页

            //关闭
            if (readyToClose)
            {
                closeForm();
            }
        }
        #endregion

        #region 匹配数据

        ///  <summary>
        /// 4、匹配数据。加工情形、情节
        ///  </summary>
        ///  <param name="inputText">文本</param>
        ///  <param name="caseid">案例ID</param>
        ///  <param name="paragraphId">逻辑段类型</param>
        ///  <param name="caseCauseId">情形分组（如“犯罪相关情形ID”)</param>
        /// <param name="conditiondt">要匹配的节点集合</param>
        public void execute_Match(string inputText, string caseid, string paragraphId, string caseCauseId, DataTable conditiondt, string singleCCID, string doubleCCID, string caseId)//第一层情形情节（conditiondt限定规则范围）
        {
            string resultText = string.Empty;//总的结果
            //2017-07-10 ljj 修改
            DataRow[] arrayDr = conditiondt.Select("RegCount > 0 and CC_ID='" + caseCauseId + "'", "CC_SerialNumb");//查找情形分组的下级（如“犯罪相关情形”的下级）
            if (arrayDr.Length == 1)
            {  //arrayDr = conditiondt.Select("RegCount > 0 and CC_ParentID='" + caseCauseId + "'", "CC_SerialNumb");
               //2017-07-10 ljj 修改
               //for (int j = arrayDr.Length - 1; j >= 0; j--)//第一级
               //{
                string ccRegexInfoCode = arrayDr[0]["CC_RegexInfoCode"].ToString();
                string ccId = arrayDr[0]["CC_ID"].ToString();
                int regCount = Convert.ToInt32(arrayDr[0]["RegCount"].ToString());
                int childCount = Convert.ToInt32(arrayDr[0]["ChildCount"].ToString());
                var ccNodeType = Convert.ToInt32(arrayDr[0]["CC_NodeType"].ToString());
                var keywords = arrayDr[0]["keywords"].ToString();
                var ruleItem = arrayDr[0]["RuleItem"].ToString();

                //4、匹配数据。过程：用“表述”（1的结果）匹配“节点”（3的结果），得出结果，结果如：
                // 盗窃数额较大(单一)            --被告人秘密窃取他人财物，数额较大，其行为已构成盗窃罪，依法应予惩处。
                // 盗窃数额较大+结伙盗窃（组合） --被告人伙同他人秘密窃取公私财物，数额较大，其行为已构成盗窃罪，依法应予惩处。
                //2017-07-10 ljj 修改
                MatchChild(conditiondt, inputText, ccId, ccRegexInfoCode, regCount, childCount, ccNodeType, keywords, ruleItem, ref resultText);

                //MatchChild(conditiondt, inputText, ccId, ccRegexInfoCode, regCount, childCount, ccNodeType, keywords, ruleItem, ref resultText);
                // }

                if (!string.IsNullOrEmpty(resultText))
                {
                    //if (resultText != caseCauseId && resultText.Contains(caseCauseId))
                    //{
                    //    resultText = resultText.Replace(caseCauseId + ",", "");
                    //}
                    string ccIdList = resultText;
                    Log.WriteLog("表述文本：" + inputText + "匹配节点:" + ccIdList);
                    //5、 匹配后的结果入库。表述节点（如：盗窃数额较大、盗窃数额较大+结伙盗窃）存入SYS_Express_MatchSituation
                    // 表述文本（如：被告人秘密窃取他人财物，数额较大，其行为已构成盗窃罪，依法应予惩处。）存入SYS_Express_Word_Process
                    AddToExpress(inputText, caseid, paragraphId, caseCauseId, ccIdList, singleCCID, doubleCCID, caseId);
                }
            }
        }

        /// <summary>
        /// 当前节点及其所有下级是否匹配
        /// </summary>
        /// <param name="conditiondt">节点集合（不用频繁查询数据库）</param>
        /// <param name="oneinputText">原文本 表述</param>
        /// <param name="ccId">节点</param>
        /// <param name="ccRegexInfoCode">节点对应正则编号（节点来源默认：判决书）</param>
        /// <param name="regCount">正则信息单元下的正则表达式个数</param>
        /// <param name="childCount">节点的下级个数</param>
        /// <param name="keywords">关键词</param>
        /// <param name="ruleItem">xml</param>
        /// <param name="resultText">返回结果</param>
        /// <param name="ccNodeType">节点类型</param>
        /// <returns></returns>
        public bool MatchChild(DataTable conditiondt, string oneinputText, string ccId, string ccRegexInfoCode, int regCount, int childCount, int ccNodeType, string keywords, string ruleItem, ref string resultText)//CC_ID 及以下是不是有匹配
        {
            int matchNumber = 1;//没正则，默认匹配
            if (regCount > 0)  //有正则
            {
                oneinputText = oneinputText.Replace("\r\n", "").Trim();
                matchNumber = IsMatch(oneinputText, ccRegexInfoCode);
            }
            //2017-07-10 ljj 修改
            //else  //匹配关键字
            //{
            //    matchNumber = IsMatchKeywords(oneinputText, ccNodeType, keywords, ruleItem);
            //}
            #region
            if (matchNumber == 1)//节点匹配表述
            {
                bool child = false;//所有子节点都不匹配时，数据才会挂到父级

                //todo 判断当前节点的子节点是否存在匹配项，如果没有匹配的子节点，那当前节点才可以匹配，否则继续递归匹配子节点
                if (childCount > 0)
                {
                    //2017-07-10 ljj 修改 子节点正则条数大于0并且不等于xml属性的子节点
                    DataRow[] arrayDr = conditiondt.Select("RegCount > 0 and CC_ParentID='" + ccId + "' and CC_NodeType<>12 ", "CC_SerialNumb");
                    for (int i = arrayDr.Length - 1; i >= 0; i--)
                    {
                        bool mat = MatchChild(conditiondt, oneinputText, arrayDr[i]["CC_ID"].ToString(),
                            arrayDr[i]["CC_RegexInfoCode"].ToString(), Convert.ToInt32(arrayDr[i]["RegCount"].ToString()),
                            Convert.ToInt32(arrayDr[i]["ChildCount"].ToString()), Convert.ToInt32(arrayDr[i]["CC_NodeType"].ToString()), arrayDr[i]["keywords"].ToString(), arrayDr[i]["RuleItem"].ToString(), ref resultText);
                        if (mat)
                        {
                            child = true;
                        }
                    }
                }
                //if (!child && regCount > 0)
                if (!child)//下级没有匹配到(没写正则不挂数据)，所有子集都不匹配，挂父节点
                {
                    if (resultText == "")
                    {
                        resultText = ccId;
                    }
                    else
                    {
                        resultText += "," + ccId;
                    }
                }
                return true;
            }
            #endregion
            return false;
        }

        /// <summary>
        /// 正则是否匹配
        /// </summary>
        /// <param name="inputText">文本</param>
        /// <param name="ccRegexInfoCode">节点对应正则编号（节点来源默认：判决书）</param>
        /// <returns></returns>
        public int IsMatch(string inputText, string ccRegexInfoCode)
        {
            if (getregex.IsMatch(ccRegexInfoCode, inputText))//匹配 CC_RegexInfoCode为编号
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 关键字是否匹配
        /// </summary>
        /// <param name="inputText">文本（源）</param>
        /// <param name="ccNodeType">节点类型</param>
        /// <param name="keywords">关键字</param>
        /// <param name="ruleItem">xml</param>
        /// <returns></returns>
        public int IsMatchKeywords(string inputText, int ccNodeType, string keywords, string ruleItem)
        {
            if (ccNodeType == 2)
            {
                if (!string.IsNullOrEmpty(keywords))
                {
                    return getregex.IsMatchKeyWord(inputText, keywords) ? 1 : 0;  //关键字匹配
                }
                return 0;
            }
            else
            {
                if (!string.IsNullOrEmpty(ruleItem))
                {
                    return getregex.IsMatchKeyWordXML(inputText, ruleItem) ? 1 : 0; //xml匹配
                }
                return 0;
            }
        }

        #endregion

        #region 隐私处理 
        /// <summary>
        /// 隐私处理
        /// </summary>
        /// <param name="ParagraphText"></param>
        /// <param name="CaseId"></param>
        /// <returns></returns>
        public string Privacy(string ParagraphText, string fieldValue)
        {
            #region 隐私处理
            //ParagraphText = "被告人谢荣兵已经着手实施盗窃犯罪，由于意志以外的原因而未得逞，系犯罪未遂。";
            //CaseId = "1000249";
            try
            {
                //2017-6-21 ljj 修改，不每次从数据库中获取隐私处理数据
                string Fields = fieldValue.Replace("，", ",");//datas.ExceptAdditionalFields(CaseId).Replace("，", ",");
                Fields = Fields.Replace(",", "|").Replace("，", "|").Replace("*", @"\*").Trim();//取人名
                if (Fields != "")
                {
                    ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, Fields, "×××");//挖空人名
                }
                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "[\\d,，.．一二三四五六七八九十万千百亿]+[百千万]?余?(?=元)", "***", RegexOptions.Singleline);
                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "(×××|\\*\\*\\*)[、|，|,]*(?=(×××|\\*\\*\\*))", "", RegexOptions.Singleline);

                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "^\\s*[“\"\\、……）\\]}】、,，。.：:；;\\d（\\(\\)） 两一二三四五六七八九但]*", "");
                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "^\\s*(本院认为|本院认为)[,:，：]*", "");
                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "[；|;]$", "。");
                //ParagraphText = getregex.GetParseValue("CC1508221657230001", ParagraphText);//排除金额，多×××
                //ParagraphText = getregex.GetParseValue("CC1508211030520001", ParagraphText);//排除某些字符
                return ParagraphText;//排除某些字符

            }
            catch (Exception error)
            {
                error.ToString();
                return ParagraphText;
            }
            #endregion
        }
        #endregion

        #region 入库
        /// <summary>
        /// 添加表述
        /// </summary>
        /// <param name="CaseCauseID">案由小分类ID</param>
        /// <param name="ParagraphID">逻辑段140，150</param>
        /// <param name="resultText">索引句子</param>
        /// <param name="CC_IDList">ID字符串</param>
        /// <param name="caseid">案例ID</param>
        public void AddToExpress(string resultText, string caseid, string ParagraphID, string CaseCauseID, string CC_IDList, string singleCCID, string doubleCCID, string caseId)
        {
            SYS_Express_Word wordModel = new SYS_Express_Word();

            try
            {
                #region 添加match表

                #region 节点属性
                //构成1 不构成0
                bool ismatchb = getregex.IsMatch("3F53BB8A-08CC-4F55-89A9-8EAAE4FC3163", resultText);//true 不构成
                int ismatch = ismatchb ? 0 : 1;
                bool affirmIdeaResultb = getregex.IsMatch("EI1601201151020001", resultText);//true 不认定
                //认定1不认定2
                string affirmIdeaResult = affirmIdeaResultb ? "2" : "1";
                var stiuModel = new SYS_Express_MatchSituation
                {
                    IsMatch = ismatch,
                    MatchSource = "0",
                    AffirmIdeaResult = affirmIdeaResult,
                    AffirmIdeaSource = "0"
                };

                #endregion



                string msId = "";

                //组合情形
                string[] situationIDa = CC_IDList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                #region 插入结果集表
                PresentationResults presentationModel = new PresentationResults();
                presentationModel.CauseId = caseId;
                presentationModel.Flag = situationIDa.Length == 1 ? 0 : 1;
                presentationModel.Presentation = resultText;
                presentationModel.PresentationRelation = CC_IDList;
                if (!presentationbll.IsExsitsPresentationData(presentationModel))
                {
                    presentationbll.AddPresentation(presentationModel);
                }
                #endregion


                //2017-07-13 ljj 修改
                if (situationIDa.Length == 1)
                {
                    msId = work.AddSingleMatch(situationIDa[0], CaseCauseID, situationIDa[0], CaseCauseID, stiuModel, "-1", true);//从0开始
                }
                else if (situationIDa.Length > 1)
                {
                    //首先判断结果集表有没有数据，没有则插入，如果有，则遍历结果的组合判断是否包含本次结果
                    DataTable dtPresentation = presentationbll.GetPresentationData(presentationModel.PresentationRelation, caseId);
                    if (dtPresentation != null && dtPresentation.Rows.Count > 0)
                    {
                        msId = GetMSId(situationIDa, stiuModel, doubleCCID, dtPresentation);
                        //没有匹配上，按照靠左匹配机制依次递减
                        if (string.IsNullOrEmpty(msId))
                        {
                            List<string[]> strs = PermutationAndCombination<string>.GetPermutation(situationIDa);
                            foreach (string[] item in strs)
                            {
                                List<string> removeIds = new List<string>();
                                List<string> dir = item.ToList();
                                for (int i = dir.Count - 1; i > 0; i--)
                                {
                                    if (!removeIds.Contains(dir[i]))
                                    {
                                        removeIds.Add(dir[i]);
                                    }
                                    dir.RemoveAt(i);
                                    string[] dirs = dir.ToArray();
                                    msId = GetMSId(dirs, stiuModel, doubleCCID, dtPresentation);
                                    if (!string.IsNullOrEmpty(msId))
                                    {
                                        SYS_Express_MatchSituation sm = MatchSituationbll.GetMatchSituation(msId);
                                        string allCombinePid = sm.AllStituationIDs;
                                        string allMsIdPid = sm.AllParentID;
                                        for (int k = 0; k < removeIds.Count; k++)
                                        {
                                            allCombinePid = allCombinePid + "," + removeIds[k];
                                            if (allMsIdPid != "")
                                                allMsIdPid += "," + msId;
                                            msId = work.AddMatch(situationIDa[i], msId, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);
                                        }
                                        break;
                                    }
                                }
                                if (string.IsNullOrEmpty(msId))
                                {
                                    string allCombinePid = situationIDa[0];
                                    string allMsIdPid = doubleCCID;

                                    msId = work.AddMatch(situationIDa[0], CaseCauseID, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);//从0开始
                                    for (int i = 1; i < situationIDa.Length; i++)
                                    {
                                        allCombinePid = allCombinePid + "," + situationIDa[i];
                                        if (allMsIdPid != "")
                                            allMsIdPid += "," + msId;
                                        else
                                            allMsIdPid += msId;

                                        msId = work.AddMatch(situationIDa[i], msId, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);
                                    }
                                    break;
                                }
                            }

                        }
                    }
                    else
                    {
                        string allCombinePid = situationIDa[0];
                        string allMsIdPid = doubleCCID;

                        msId = work.AddMatch(situationIDa[0], CaseCauseID, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);//从0开始
                        for (int i = 1; i < situationIDa.Length; i++)
                        {
                            allCombinePid = allCombinePid + "," + situationIDa[i];
                            if (allMsIdPid != "")
                                allMsIdPid += "," + msId;
                            else
                                allMsIdPid += msId;

                            msId = work.AddMatch(situationIDa[i], msId, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);
                        }
                    }
                }
                #endregion

                #region 添加文本

                wordModel.MS_ID = msId;


                wordModel.EW_CaseId = caseid;
                wordModel.EW_Content = resultText;

                wordModel.EW_UseCount = 1;
                wordModel.EW_WordCount = resultText.Length;
                wordModel.ParagraphTypeId = Convert.ToInt32(ParagraphID);

                if (situationIDa.Length == 1) wordModel.EW_IsSingleExpress = 1;
                else wordModel.EW_IsSingleExpress = 0;

                wordModel.EW_ID = wordbll.Exists_WordProcess(wordModel);
                if (getregex.IsMatch("EI1908120910240001", resultText))
                {
                    wordModel.EW_UserID = "1";
                }
                if (wordModel.EW_ID == "")
                {
                    wordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                    wordModel.EW_Right = 0;
                    wordModel.EW_Wrong = 0;

                    wordbll.AddWord_Process(wordModel);
                }
                else
                {
                    wordbll.UpdateWord_Process(wordModel);
                }
                #endregion

                #region 词库
                var ewAddElementStr = express_wordbankrelbll.WordBank("", wordModel.EW_Content);

                foreach (var item in ewAddElementStr)
                {
                    if (!express_wordbankrelbll.Exists(wordModel.EW_ID, item))
                    {

                        express_wordbankrelbll.Add_Express_WordBankRel(newid.JudgeDoc_CreateID("SYS_Express_WordBankRel"), wordModel.EW_ID, item);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Log.WriteLog("AddToExpress报错：" + "ew_id:" + wordModel.EW_ID + "  msid:" + wordModel.MS_ID + " ew_Content:" + wordModel.EW_Content + " ew_IsSingleExpress:" + wordModel.EW_IsSingleExpress);
                throw;
            }
        }
        #endregion

        #region 从结果集中获取是否存在msid
        /// <summary>
        /// 从结果集中获取是否存在msid
        /// </summary>
        /// <param name="situationIDa"></param>
        /// <param name="stiuModel"></param>
        /// <param name="doubleCCID"></param>
        /// <param name="dtPresentation"></param>
        /// <returns></returns>
        private string GetMSId(string[] situationIDa, SYS_Express_MatchSituation stiuModel, string doubleCCID, DataTable dtPresentation)
        {
            string msId = "";
            if (dtPresentation != null && dtPresentation.Rows.Count > 0)
            {
                List<string[]> strs = PermutationAndCombination<string>.GetPermutation(situationIDa);
                foreach (string[] item in strs)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (var ite in item)
                    {
                        sb.Append(ite + ",");
                    }
                    if (dtPresentation.Select(" PresentationRelation like '" + sb.ToString().Substring(0, sb.Length - 1) + "%' ").Length > 0)
                    {
                        DataRow dr = dtPresentation.Select(" PresentationRelation like '" + sb.ToString().Substring(0, sb.Length - 1) + "%' ")[0];
                        msId = MatchSituationbll.Exists_MatchSituation(item[item.Length - 1], stiuModel.IsMatch, stiuModel.MatchSource, stiuModel.AffirmIdeaResult, stiuModel.AffirmIdeaSource, sb.ToString().Substring(0, sb.Length - 1), item[item.Length - 2], doubleCCID);//存在
                        if (string.IsNullOrEmpty(msId))
                        {
                            System.Windows.Forms.MessageBox.Show("获取已存在的msid出错!");
                            Log.WriteLog("获取已存在的msid出错!");
                        }
                        break;

                    }
                }
            }
            else
            {
                return "";
            }
            return msId;
        }
        #endregion


        public void CLdata()
        {
            Express_MatchSituationDAL dal = new Express_MatchSituationDAL();
            DataTable dt = dal.GetExpressData();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string CC_TextCRCCode = dr[0].ToString();
                    DataTable dt1 = dal.GetExpressDataByCode(CC_TextCRCCode);
                    if (dt1 != null && dt1.Rows.Count > 0)
                    {
                        List<string> ccids = new List<string>();
                        foreach (DataRow item in dt1.Rows)
                        {
                            ccids.Add(item["CauseId"].ToString());
                        }

                        string ccid = dt1.Rows[0]["CauseId"].ToString();
                        string CaseCauseID = BelongCaseCauseId(ccid);
                        string resultText = dt1.Rows[0]["CC_Text"].ToString();
                        string caseid = dt1.Rows[0]["CaseId"].ToString();

                        //bool ismatchb = getregex.IsMatch("3F53BB8A-08CC-4F55-89A9-8EAAE4FC3163", resultText);//true 不构成
                        //int ismatch = ismatchb ? 0 : 1;
                        //bool affirmIdeaResultb = getregex.IsMatch("EI1601201151020001", resultText);//true 不认定
                        //                                                                            //认定1不认定2
                        //string affirmIdeaResult = affirmIdeaResultb ? "2" : "1";
                        var stiuModel = new SYS_Express_MatchSituation
                        {
                            IsMatch = 1,
                            MatchSource = "0",
                            AffirmIdeaResult = "1",
                            AffirmIdeaSource = "0"
                        };
                        string[] situationIDa = ccids.ToArray();

                        string allCombinePid = situationIDa[0];
                        string allMsIdPid = "M" + CaseCauseID;
                        string msId = "";

                        msId = work.AddMatch(situationIDa[0], CaseCauseID, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);//从0开始
                        for (int i = 1; i < situationIDa.Length; i++)
                        {
                            allCombinePid = allCombinePid + "," + situationIDa[i];
                            if (allMsIdPid != "")
                                allMsIdPid += "," + msId;
                            else
                                allMsIdPid += msId;

                            msId = work.AddMatch(situationIDa[i], msId, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);
                        }

                        SYS_Express_Word wordModel = new SYS_Express_Word();

                        wordModel.MS_ID = msId;


                        wordModel.EW_CaseId = caseid;
                        wordModel.EW_Content = resultText;

                        wordModel.EW_UseCount = 1;
                        wordModel.EW_WordCount = resultText.Length;

                        wordModel.EW_IsSingleExpress = 0;
                        wordModel.EW_Right = 0;
                        wordModel.EW_Wrong = 0;
                        wordModel.EW_ID = wordbll.Exists_WordProcess(wordModel);

                        if (getregex.IsMatch("EI1908120910240001", resultText))
                        {
                            wordModel.EW_UserID = "1";
                        }
                        if (wordModel.EW_ID == "")
                        {
                            wordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                            wordbll.AddWord_Process(wordModel);
                        }
                        else
                        {
                            wordbll.UpdateWord_Process(wordModel);
                        }
                    }
                }
            }
            System.Windows.Forms.MessageBox.Show("执行完毕");
        }

        public string BelongCaseCauseId(string ccId)
        {
            string caseCauseId = "";
            CaseCauseBLL casecausebLL = new CaseCauseBLL();

            //获取节点信息
            DataTable dtStiuid = casecausebLL.GetSYS_CaseCauseByCCID(ccId);

            if (dtStiuid.Rows.Count > 0)
            {
                int ccNodeType = Convert.ToInt32(dtStiuid.Rows[0]["CC_NodeType"]);
                int ccIsProcessNode = Convert.ToInt32(dtStiuid.Rows[0]["CC_IsProcessNode"]);
                //案由
                if (ccIsProcessNode == 1)  //匹配表述根节点
                {
                    caseCauseId = dtStiuid.Rows[0]["CC_ID"].ToString();
                }
                else   //普通节点
                {
                    caseCauseId = casecausebLL.IsParentRealation1(ccId).CC_ID;
                    return BelongCaseCauseID_NormalNote(ccId).Rows[0]["CC_ID"].ToString();
                }
            }
            return caseCauseId;
        }
        public DataTable BelongCaseCauseID_NormalNote(string ccId)
        {
            CaseCauseBLL casecausebLL = new CaseCauseBLL();
            DataTable dtStiuid = casecausebLL.GetSYS_CaseCauseByCCID(ccId);
            while (dtStiuid.Rows.Count > 0 && Convert.ToInt32(dtStiuid.Rows[0]["CC_IsProcessNode"]) != 1)//不是情形情节分组的节点，向上查
            {
                dtStiuid = casecausebLL.GetSYS_CaseCauseByCCID(dtStiuid.Rows[0]["CC_ParentID"].ToString());
            }

            return dtStiuid;
        }

    }
}